package com.ggh.service.impl;
import	java.nio.file.attribute.BasicFileAttributeView;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ggh.dao.AiMapper;
import com.ggh.entity.Ai;
import com.ggh.entity.RoomBeanP;
import com.ggh.entity.User;
import com.ggh.entity.UserBean;
import com.ggh.handler.GameService;
import com.ggh.handler.MatchingRoomP;
import com.ggh.handler.Public_State_P;
import com.ggh.handler.Public_State_PSiRen;
import com.ggh.service.AiService;
import com.ggh.util.JsonUtils;
import com.ggh.vo.Body;
import com.ggh.websocket.PK_WebSocket_P;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author jj
 * @date 2019/10/22 12:10
 * 机器人实现
 */
@Service
public class AiServiceImpl extends ServiceImpl<AiMapper, Ai> implements AiService {

    private GameService gameService=new GameService();
    /**
    * @description : 向游戏内添加机器人
    * @param aiUser 
    * @date : 2019/10/23 9:32
    * @author : jj
    */
    @Override
    public Body addGame(Ai aiUser) {
        Ai ai = baseMapper.selectOne(new QueryWrapper<Ai>().eq("userid",aiUser.getUserid()).eq("enable",0));
        UserBean user= ai!=null? createUser(ai): null;
        if (user != null) {
            if (StringUtils.isNotEmpty(ai.getRooomno())) {
                RoomBeanP roomBeanP = Public_State_PSiRen.roomMap.get(ai.getRooomno());
                if (roomBeanP!=null){
                    int zb= (int) roomBeanP.getGame_userlist().stream().filter(us -> us.getIsAi() == 1).count();
                    if (zb>=2){
                        return Body.newInstance(405,"已存在2个机器人");
                    }
                }
                //加入房间
                HashMap matching = gameService.Matching(ai.getRooomno(), user);
                if (matching==null){
                    return Body.newInstance(405,"房间不存在");
                }
                boolean b= matching.get(1)==null||matching.get(2)!=null?true:false;
                if (b){
                    //四人房间操作
                  isActive(ai.getRooomno(),user);
                }
                ai.setEnable(1);
                ai.updateById();
                return Body.newInstance();
            }
            return Body.BODY_470;
        }
        return Body.BODY_400;
    }
    @Override
    public Body exitGame(Ai aiUser) {
            RoomBeanP roomBeanP;
            roomBeanP = Public_State_PSiRen.roomMap.get(aiUser.getRooomno());
               if (roomBeanP==null){
                   roomBeanP = Public_State_P.roomMap.get(aiUser.getRooomno());
                   if (roomBeanP==null){
                       return Body.BODY_400;
                   }
               }
            UserBean userBean = roomBeanP.getUserBean(aiUser.getUserid());
            if (userBean==null){
                return Body.BODY_400;
            }
            //退出
            userBean.setExit_state(1);
            userBean.setReady_state(2);
            userBean.setExit_state(1);
            Ai ai = baseMapper.selectOne(new QueryWrapper<Ai>().eq("userid",userBean.getUserid()).eq("enable",1));
            ai.setEnable(0);
            ai.updateById();
        return Body.BODY_400;
    }
    /**
    * @description :创建游戏user并上传ai属性
    * @param ai 
    * @date : 2019/10/22 14:27
    * @author : jj
    */
    private UserBean createUser(Ai ai){
        UserBean user=new UserBean();
        BeanUtils.copyProperties(ai,user);
        user.setIsAi(1);
        System.out.println(user);
        return  user;
    }

    /**
     * 检查是否在四人房间
     * @param roomno
     * @return
     */
    private void isActive(String roomno,UserBean user){
        RoomBeanP roomBeanP = Public_State_PSiRen.roomMap.get(roomno);
        if (roomBeanP!=null){
            HashMap<String,Object> map=new HashMap<> ();
            map.put("type","SiRenEnterRoomAll");
            map.put("messages", JsonUtils.get().toJson(roomBeanP));
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sendMessageAll(map, roomBeanP);
            MatchingRoomP.getready(user, roomBeanP);
            map.clear();
            map.put("type", "SiRenPlayerReadyAll");
            map.put("messages", user.getUserid());
            sendMessageAll(map,roomBeanP);
            boolean gameStart = isGameStart(roomBeanP);
            /*判断是否可以开始游戏*/
            if (gameStart){
                map.clear();
                map.put("type","SiRenInciDent");
                map.put("messages", JsonUtils.get().toJson(roomBeanP));
                sendMessageAll(map, roomBeanP);

            }

        }
    }

    /**
     * 是否可以开始
     * @return
     */
    public boolean isGameStart(RoomBeanP room) {
        // 判断房间中准备人数
        int zb = 0;
        for (int i = 0; i < room.getUser_positions().length; i++) {
            if (room.getUser_positions()[i] != -1) {
                zb++;
            }
        }
        if (zb == room.getGame_userlist().size() && zb > 2) {
            /*添加对局数*/
            if (room.getGame_number() == 0) {
                room.setGame_number(1);
            }
            // 有2个人准备（坐下）,修改房间状态
            room.setState(1);
            // 赋值房间时间.房间今日准备倒计时
            room.setTime(room.getTime01());
            return true;
        }
        return false;
    }
    /**
     * @description :发送消息给所有人
     * @param returnMap
     * @param rb
     * @return: void
     * @date : 2019/10/8 15:36
     * @author : jj
     * @throws
     */
    public synchronized void sendMessageAll(Map<String, Object> returnMap, RoomBeanP rb) {
        for (UserBean userb : rb.getGame_userlist()) {
            PK_WebSocket_P webSocket = Public_State_P.clients.get(String.valueOf(userb.getUserid()));
            if (webSocket != null && webSocket.getSession().isOpen() && userb.getExit_state() == 0&&userb.getIsAi()==0) {
                // 不等于自己的则发送消息
                webSocket.sendMessageTo(returnMap, userb);
            } else {
                continue;
            }
        }
    }
}
